package edu.taru.office.util;

import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

/**
 * 图片工具类
 */
public class ImageUtil {

    /**
     * 保存图片
     * @param multipartFile
     * @param path
     */
    public static String save(MultipartFile multipartFile, String path) throws  Exception{
        File file = new File(path);
        if (!file.exists()) {
            file.mkdirs();
        }

        FileInputStream fileInputStream = (FileInputStream) multipartFile.getInputStream();
        String fileName = multipartFile.getOriginalFilename();
        String tail= fileName.substring(fileName.lastIndexOf("."));
        String newname=String.valueOf(System.currentTimeMillis()).concat(tail);
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(path + File.separator + newname));
        byte[] bs = new byte[1024];
        int len;
        while ((len = fileInputStream.read(bs)) != -1) {
            bos.write(bs, 0, len);
        }
        bos.flush();
        bos.close();
        return newname;

    }
}
